package cn.itcast.bassm.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.itcast.bassm.mapper.UserMapper;
import cn.itcast.bassm.pojo.Timeend;
import cn.itcast.bassm.service.InputandUpdowService;
import cn.itcast.bassm.util.readTxT;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
@Service
public class InputandUpdowServiceImpl implements InputandUpdowService{
	
	
    public InputandUpdowServiceImpl() {  
        super();  
        // TODO Auto-generated constructor stub  
    } 
	
	
	
	@Autowired
	private  UserMapper userMapper;
	private static Logger mLogger = Logger.getLogger("InputandUpdowService");
	private final static String CONTENT_TYPE_TEXT_JSON = "text/json";
	static String Localfaceuser="admin";
	static String passwork="123456";
	public  String getUser(){
		Timeend timeend = new Timeend();
		String id ="1";
		String de ="0";
		//String txtPathid ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
		String txtPathid ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
		String idnumber=readTxT.readTxtLine(txtPathid, 4);
		JsonObject object2 = new JsonObject();
			timeend = userMapper.secleTimeEnd(id);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			if(timeend.getTimesetend()==null||timeend.getTimesetend()==""){
				Date data=new Date();
		        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        String updatetime = dateFormat.format(data);
		        String starttime="2000-01-01 00:00:00";
		        object2.addProperty("starttime", starttime);
			}else {
				String starttime=timeend.getTimesetend();
				object2.addProperty("starttime", starttime);
			}			
	        object2.addProperty("idnumber", idnumber);

			String jsonstr = object2.toString(); 
			String personServerurl="http://wwl.ycws.cc/ssm/v2/wwluserinfo";
	        String json =doPostJsonone(personServerurl,jsonstr);
	       if (json != null) {
	    	   JsonParser parser = new JsonParser(); // 创建JSON解析器
               JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
               String timesetend=object.get("systemtime").getAsString();
              JsonArray jsonone= object.getAsJsonArray("list");
              for (int i = 0; i < jsonone.size(); i++) {
            	  JsonObject subObject=jsonone.get(i).getAsJsonObject();
            	  String yindex = subObject.get("yindex").getAsString();
            	  String facepath = subObject.get("yfilename").getAsString(); 
            	  if(facepath !=null||facepath !=""){
            	  if(yindex.equals(id)){// 判断是不是为"1"，导入枪击
            		  String phone = subObject.get("yid").getAsString();
            		  String idCard=phone; 
            		  long nuberone = getUserID(idCard);
            		  String nuberotwo = String.valueOf(nuberone);//	先查询是否有次账号 0没有找到 00查询出问题
            		  String tong ="0";
            		  String tongtwo="00";
            		  if(nuberotwo.equals(tong)){
            			  String name = subObject.get("yname").getAsString();
            			  String sex = subObject.get("ysex").getAsString();
            			  String validTo1 = subObject.get("idnumber").getAsString(); 
            			  try {
            				  addWhitePersion(facepath, name, phone,sex,validTo1);
            			  } catch (Throwable e) {
            				  e.printStackTrace();
            			  }
            		  		}else if(nuberotwo.equals(tongtwo)){
            		  			System.out.println("查询用户出现错误");
            		  		}
            		  		else {//更新
						System.out.println("号码"+phone+"已经存在所以先删除");
						String phonedele = subObject.get("yid").getAsString();
	            		  long nuberonedele = getUserID(phonedele);
	            		  String idnuberone = String.valueOf(nuberonedele);//查询用户在枪击后台里面的ID
	            		  String txtPath ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
	            		  	//String txtPath="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
	      					String TimeSex=readTxT.readTxtLine(txtPath, 1);
	      					String urlStr = TimeSex+"/api/v1/person/"+idnuberone;
	      					DeledoBasicuser(urlStr);
	      					System.out.println("删除"+phone);
	      					//导入
	      					  String name = subObject.get("yname").getAsString();
	            			  String sex = subObject.get("ysex").getAsString();
	            			  String validTo1 = subObject.get("idnumber").getAsString(); 
	            			  try {
	            				  addWhitePersion(facepath, name, phone,sex,validTo1);
	            				  System.out.println("导入成功"+phone);
	            			  } catch (Throwable e) {
	            				  e.printStackTrace();
	            			  }
            		  		}
            	  		}else if(yindex.equals(de)){// 判断是不是为"2"，从枪击里面删除
            		  String phone = subObject.get("yid").getAsString();
            		  long nuberone = getUserID(phone);
            		  String idnuberone = String.valueOf(nuberone);//查询用户在枪击后台里面的ID
            		  String txtPath ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
            		  //String txtPath="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
      					String TimeSex=readTxT.readTxtLine(txtPath, 1);
      					String urlStr = TimeSex+"/api/v1/person/"+idnuberone;
      					DeledoBasicuser(urlStr);
      					System.out.println("删除"+phone);
            	  		}
            	  }else {
      				System.out.println("没有图片地址");
      			}
              	}
              JsonArray jsontwo= object.getAsJsonArray("list1");
              for (int i = 0; i < jsontwo.size(); i++) {
            	  JsonObject subObject=jsontwo.get(i).getAsJsonObject();
            	  String yindate = subObject.get("yindate").getAsString();
            	  String facepath = subObject.get("yimageurl").getAsString();
            	  if(facepath!=null||facepath!=""){
            	  if(yindate.equals(id)){//  判断是不是为"1"，导入枪击
            		  String phonelike = subObject.get("yid").getAsString();
            		  String phone = "00"+phonelike;
            		  String idCard=phone;
            		  long nuberone = getUserID(idCard);
            		  String nuberotwo = String.valueOf(nuberone);//先查询是否有次账号
            		  String tong ="0";
            		  String tongtwo="00";
            		  if(nuberotwo.equals(tong)){
            			  String name = subObject.get("yname").getAsString();
            			  String sex = subObject.get("ysex").getAsString();
            			  String validTo1 = subObject.get("state").getAsString(); 
            			  try {
            				  addWhitePersion(facepath, name, phone,sex,validTo1);
            			  } catch (Throwable e) {
            				  e.printStackTrace();
            			  }
            		  }else if(nuberotwo.equals(tongtwo)){
      		  			System.out.println("查询用户出现错误");
      		  		}
            		  else {
            			  System.out.println("号码"+phone+"已经存在先删除");
            			  String phonelikedele = subObject.get("yid").getAsString();
                		  String phonedele = "00"+phonelikedele;
                		  long nuberonedele = getUserID(phonedele);
                		  String idnuberone = String.valueOf(nuberonedele);//查询用户在枪击后台里面的ID
                		  String txtPath ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
                		  	//String txtPath="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
          					String TimeSex=readTxT.readTxtLine(txtPath, 1);
          					String urlStr = TimeSex+"/api/v1/person/"+idnuberone;
          					DeledoBasicuser(urlStr);
          					System.out.println("删除"+phone);
          					//导入
          					String name = subObject.get("yname").getAsString();
              			  String sex = subObject.get("ysex").getAsString();
              			  String validTo1 = subObject.get("state").getAsString(); 
              			  try {
              				  addWhitePersion(facepath, name, phone,sex,validTo1);
              			  } catch (Throwable e) {
              				  e.printStackTrace();
              			  }
					}
            	  }else if(yindate.equals(de)){// 判断是不是为"2"，从枪击里面删除
            		  String phonelike = subObject.get("yid").getAsString();
            		  String phone = "00"+phonelike;
            		  long nuberone = getUserID(phone);
            		  String idnuberone = String.valueOf(nuberone);//查询用户在枪击后台里面的ID
            		  String txtPath ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
            		  //String txtPath="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
      					String TimeSex=readTxT.readTxtLine(txtPath, 1);
      					String urlStr = TimeSex+"/api/v1/person/"+idnuberone;
      					DeledoBasicuser(urlStr);
      					System.out.println("删除"+phone);
				}
              }else {
				System.out.println("没有图片地址");
			}

              }
              
              userMapper.uptimeend(timesetend, id);
	        } else {
	            System.out.println("json出现错误了");
	        }
		System.out.println("y");
		return null;
	}
	//}
	
	
	public static String doPost(String urlStr, List<NameValuePair> params) {
        String result = null;
        HttpPost httpPost = new HttpPost(urlStr);

        try {
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
            httpPost.setEntity(entity);// 设置参数实体
            @SuppressWarnings("resource")
            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);// 连接超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);// 请求超时

            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
            } else {
                mLogger.info("doPost getStatusCode " + httpResp.getStatusLine().getStatusCode());
            }

        } catch (ConnectTimeoutException e) {
            mLogger.info("doPost ConnectTimeoutException " + e.toString());
        } catch (UnsupportedEncodingException e) {
            mLogger.info("doPost UnsupportedEncodingException " + e.toString());
        } catch (IOException e) {
            mLogger.info("doPost IOException " + e.toString());
        } catch (Exception e) {
            mLogger.info("doPost Exception " + e.toString());
        }

        return result;
    }
	
	/**
	 * 人脸检测和导入数据
	 * @param state 
	 * @param sfzid 
	 * @throws Throwable 
	 */
	public  void addWhitePersion(String facepath, String name, String phone,String sex, String validTo1) throws Throwable {
		boolean ret = false;
		 String imgpath = facepath.toLowerCase();
		 if (imgpath.contains(".png")) {
                imgpath = png2jpg(imgpath);
            }
		 
		 if (imgpath.contains(".jpg")) {
			 List<String> retList = detectFace(imgpath);
			 if(retList != null && retList.size() == 2){
			 int gender=0;
			 if(sex.equals("男")){
				 gender=1;
			 }
			 String txtPath ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
			 //String txtPath="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
			 String TimeSex=readTxT.readTxtLine(txtPath, 1);
			 String personImportServer =TimeSex+"/api/v1/person/import";
			 String TimeSex2=readTxT.readTxtLine(txtPath, 2);

			 String personImportServer1 =TimeSex+"/api/v1/person/import";
			 long dbid = Long.valueOf(TimeSex2).longValue();
			 String sfzid = phone;
			 String validTo2=validTo1;
			 Date date1 = new SimpleDateFormat("yyyyMMdd").parse(validTo2);
			 String validTo= new SimpleDateFormat("yyyy-MM-dd").format(date1);
			 ret = addWhitePersionto(personImportServer1, name, gender, dbid, retList.get(0), retList.get(1),sfzid,validTo);
		 }else {
			 findownuserone(phone);
            System.out.println("下载图片出错，或者人脸检测失败");
         }
     }
 
		
	}
	
	/**
	 * 图片格式转换
	 * @param pngFile
	 * @return
	 */
	public static String png2jpg(String pngFile) {
		String newFile = null;
		if (pngFile != null && pngFile.toLowerCase().contains(".png")) {
			try {
				// read image file
				BufferedImage bufferedImage = ImageIO.read(new File(pngFile));
				newFile = pngFile.replace(".png", ".jpg");
				ImageIO.write(bufferedImage, "jpg", new File(newFile));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return newFile;
	}
	
	/**
	 * 人脸检测
	 */
	public static List<String> detectFace(String imgpath) throws Throwable {
	     String feature = null;
	        String face_image = null;
	        List<String> retList = new ArrayList<String>();
	        String json = null;
	        String txtPath ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
			String TimeSex=readTxT.readTxtLine(txtPath, 1);
	        String detectFaceFileServer=TimeSex+"/api/v1/tool/detectFaceInFile";
	        String wximgpath = getdownimg(imgpath);//下载相片     
	        if(wximgpath!=null){//判断是不是下载图片出现问题了
	        json = doPostFile(detectFaceFileServer, "file", wximgpath);
	        if (json != null) {
	            //System.out.print(json + "\n");
	            try {
	                JsonParser parser = new JsonParser(); // 创建JSON解析器
	                JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
	                int errorcode = object.get("errorCode").getAsInt();
	                if (errorcode == 0) {
	                    JsonObject dataobject = object.get("data").getAsJsonObject();
	                    if (dataobject != null) {
	                        JsonArray array = dataobject.get("result").getAsJsonArray();
	                        if (array.size() > 0) {
	                            JsonObject subObject = array.get(0).getAsJsonObject();

	                            feature = subObject.get("feature").getAsString();
	                            face_image = subObject.get("face_image").getAsString();
	                            retList.add(feature);
	                            retList.add(face_image);
	                        }
	                    }
	                		} else {
	                    mLogger.error("detectFace " + json);
	                }
	            } catch (JsonSyntaxException e) {
	                e.printStackTrace();
	            }
	        } else {
	            mLogger.error("connect detectFace error");
	        	}
	        }else {
	        	retList=null;
			}
	        return retList;
	}
	
	/**
	 * 通过url下载图片
	 */
	public static String getdownimg(String wxpath)throws Exception{
		Date data=new Date();
		String filename;
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        String newData = dateFormat.format(data);
		try {
			filename="/home/apache-tomcat-8.0.24/webapps/wximg/"+newData+"01"+".jpg";
			// 构造URL
			URL url = new URL(wxpath);
			// 打开连接
			URLConnection con = url.openConnection();
			// 输入流
			InputStream is = con.getInputStream();
			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			OutputStream os = new FileOutputStream(filename);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
			  os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
			filename=null;
		}
	    return filename;
	}
	
	public static String doPostFile(String urlStr, String paramName,String filePath) {
		 String result = null;
	        @SuppressWarnings("resource")
	        HttpClient httpclient = new DefaultHttpClient();
	        HttpPost post = new HttpPost(urlStr);
	        post.addHeader("Authorization", getHeader(Localfaceuser, passwork));
	        FileBody fileBody = new FileBody(new File(filePath));
	       
	        StringBody stringBody = null;
	        try {
	            stringBody = new StringBody(paramName);
	        } catch (UnsupportedEncodingException e) {
	            mLogger.info("doPostFile UnsupportedEncodingException " + e.toString());
	        }

	        MultipartEntity entity = new MultipartEntity();
	       
	        entity.addPart("file", fileBody);
	        entity.addPart("desc", stringBody);
	        post.setEntity(entity);

	        HttpResponse httpResp;
			try {
				
				httpResp = httpclient.execute(post);
				if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
					result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
				} else {
					mLogger.info("getStatusCode " + httpResp.getStatusLine().getStatusCode());
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	        httpclient.getConnectionManager().shutdown();
	        return result;
	}
	
 	/**
     * 构造Basic Auth认证头信息
     * 
     * @return
     */
    private static  String getHeader(String username, String password) {
        String auth = username + ":" + password;
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        return authHeader;
    }
    
	public static boolean addWhitePersionto(String personServer, String name,int gender, long dbId, String features, String face_image,String sfzid,String validTo) {
        boolean ret = false;
 /*       Calendar curr = Calendar.getInstance();
		curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);
		Date date=curr.getTime();  
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");  
		String validTo = sdf2.format(date);*/
        JsonObject object = new JsonObject();
        object.addProperty("name", name);
        object.addProperty("idCard", sfzid);
        object.addProperty("gender", gender);
        object.addProperty("dbId", dbId);
        object.addProperty("features", features);
        object.addProperty("imageData", face_image);
		object.addProperty("validTo", validTo);
        String jsonstr = object.toString();
        jsonstr = "[" + jsonstr + "]";

        String json = doPostJson(personServer, jsonstr);
        if (json != null) {
            JsonParser parser = new JsonParser(); // 创建JSON解析器
            object = (JsonObject) parser.parse(json); // 创建JsonObject对象
            int errorcode = object.get("errorCode").getAsInt();
            if (errorcode == 0) {
            	System.out.println("成功导入"+sfzid);
                ret = true;
            }
            mLogger.info(name + "  " +json);
        } else {
            mLogger.error("connect addWhitePersion error");
        }
        return ret;
	}
	
	
	public static String doPostJson(String urlStr, String jsonstr) {
        String result = null;
        HttpPost httpPost = new HttpPost(urlStr);

        try {
            httpPost.addHeader("Authorization", getHeader(Localfaceuser, passwork));
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            // httpPost.setHeader("Content-Type", "application/json");
            StringEntity se = new StringEntity(jsonstr, "UTF-8");
            se.setContentType(CONTENT_TYPE_TEXT_JSON);
            httpPost.setEntity(se);
            @SuppressWarnings("resource")
            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实
            
            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
            } else {
                mLogger.info("getStatusCode " + httpResp.getStatusLine().getStatusCode());
            }
        } catch (ConnectTimeoutException e) {
            mLogger.info("doPostJson ConnectTimeoutException " + e.toString());
        } catch (UnsupportedEncodingException e) {
            mLogger.info("doPostJson UnsupportedEncodingException " + e.toString());
        } catch (IOException e) {
            mLogger.info("doPostJson IOException " + e.toString());
        } catch (Exception e) {
            mLogger.info("doPostJson Exception " + e.toString());
        }

        return result;
	}
	
	/**
	 * 根据手机号查询瑞为枪击是否有值
	 */
    public long  getUserID(String idCard) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        String txtPath ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
        //String txtPath="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
        String TimeSex2=readTxT.readTxtLine(txtPath, 2);
		long dbid = Long.valueOf(TimeSex2).longValue();
        params.add(new BasicNameValuePair("dbIds", ""+dbid));
        params.add(new BasicNameValuePair("idCard", idCard));
        long userid=0;
        //接口不支持精确查询
        String txtPath1 ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
        //String txtPath1="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
		String TimeSex=readTxT.readTxtLine(txtPath1, 1);
        String personQueryServer = TimeSex+"/api/v1/person/query";
        String json = DeledoBasicAuthPost(personQueryServer, params);
        if (json != null) {
            JsonParser parser = new JsonParser(); // 创建JSON解析器
            JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
            int errorcode = object.get("errorCode").getAsInt();
            if (errorcode == 0) {
                JsonObject dataobject = object.get("data").getAsJsonObject();
                if (dataobject != null) {
                    JsonArray array = dataobject.get("content").getAsJsonArray();
                    for (int i = 0; i < array.size(); i++) {
                        JsonObject subObject = array.get(i).getAsJsonObject();
                        String idCard1 = subObject.get("idCard").getAsString();
                        if (idCard1 != null && idCard1.equals(idCard)) {
                            userid = subObject.get("id").getAsLong();
                            break;
                        }
                    }
                }
            }
        } else {
           System.out.println("查询出错了");
           userid =00;
        }
        
        return userid;
    }
    
    public String DeledoBasicAuthPost(String urlStr, List<NameValuePair> params) {
        String result = null;
        HttpPost httpPost = new HttpPost(urlStr);

        try {
            httpPost.addHeader("Authorization", getHeader(Localfaceuser, passwork));
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集
            httpPost.setEntity(entity);// 设置参数实体
            @SuppressWarnings("resource")
            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
            } else {
                mLogger.info("doBasicAuthPost getStatusCode " + httpResp.getStatusLine().getStatusCode());
            }
        } catch (ConnectTimeoutException e) {
            mLogger.info("doBasicAuthPost ConnectTimeoutException " + e.toString());
        } catch (UnsupportedEncodingException e) {
            mLogger.info("doBasicAuthPost UnsupportedEncodingException " + e.toString());
        } catch (IOException e) {
            mLogger.info("doBasicAuthPost IOException " + e.toString());
        } catch (Exception e) {
            mLogger.info("doBasicAuthPost Exception " + e.toString());
        }

        return result;
    }
    
    /**
     * 删除用户
     */
    public String DeledoBasicuser(String urlStr) {
        String result = null;
        HttpDelete httpDelete = new HttpDelete(urlStr);

        try {
        	httpDelete.addHeader("Authorization", getHeader(Localfaceuser, passwork));
           // HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");// 设置字符集-8");
            @SuppressWarnings("resource")
            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

            HttpResponse httpResp = httpClient.execute(httpDelete);// 获取HttpResponse实例
            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
            } else {
                mLogger.info("doBasicAuthPost getStatusCode " + httpResp.getStatusLine().getStatusCode());
            }
        } catch (ConnectTimeoutException e) {
            mLogger.info("doBasicAuthPost ConnectTimeoutException " + e.toString());
        } catch (UnsupportedEncodingException e) {
            mLogger.info("doBasicAuthPost UnsupportedEncodingException " + e.toString());
        } catch (IOException e) {
            mLogger.info("doBasicAuthPost IOException " + e.toString());
        } catch (Exception e) {
            mLogger.info("doBasicAuthPost Exception " + e.toString());
        }

        return result;
    }
    
    
    /**
     * 测试接口
     */
    
    public String finsclecttestone(){
    	String msg =null;
    	String urlStr="https://wwl.ycws.cc/ssm/v1/wwlcount";
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
    	params.add(new BasicNameValuePair("id","100"));
    	params.add(new BasicNameValuePair("idnumber","IPC701269"));
    	params.add(new BasicNameValuePair("datetime","2017-7-29 10:00:00"));
    	params.add(new BasicNameValuePair("doortype","Face"));
    	String json=doPost(urlStr, params);
    	if (json != null) {
    		msg="成功";
    	}else {
			msg="失败";
		}
    	
    	return msg;
    }
    
    /**
     * 测试接口2
     * 
     */
    
    public String xintiaofin(){
    	String msg =null;
    	String urlStr="http://wwl.ycws.cc/bassm/user/Testfintwo";
    	JsonObject object2 = new JsonObject();
    	object2.addProperty("dbid", "IPC701269");
    	object2.addProperty("starttime", "2017-08-30 10:51:52");
		String jsonstr = object2.toString();
		String json=doPostJsonone(urlStr, jsonstr);
    	if (json != null) {
    		msg="成功";
    	}else {
			msg="失败";
		}
    	return msg;
    }
    
    
    public static String doPostJsonone(String urlStr, String jsonstr) {
        String result = null;
        HttpPost httpPost = new HttpPost(urlStr);

        try {
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            // httpPost.setHeader("Content-Type", "application/json");
            StringEntity se = new StringEntity(jsonstr, "UTF-8");
            se.setContentType(CONTENT_TYPE_TEXT_JSON);
            httpPost.setEntity(se);
            @SuppressWarnings("resource")
            HttpClient httpClient = new DefaultHttpClient();// 获取HttpClient对象
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);// 连接超时
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);// 请求超时

            HttpResponse httpResp = httpClient.execute(httpPost);// 获取HttpResponse实例
            if (httpResp.getStatusLine().getStatusCode() == 200) {// 判断是够请求成功
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");// 获取返回的数据
            } else {
                mLogger.info("getStatusCode " + httpResp.getStatusLine().getStatusCode());
            }
        } catch (ConnectTimeoutException e) {
            mLogger.info("doPostJson ConnectTimeoutException " + e.toString());
        } catch (UnsupportedEncodingException e) {
            mLogger.info("doPostJson UnsupportedEncodingException " + e.toString());
        } catch (IOException e) {
            mLogger.info("doPostJson IOException " + e.toString());
        } catch (Exception e) {
            mLogger.info("doPostJson Exception " + e.toString());
        }

        return result;
    }
    
   public  void findownuserone(String id){
	   String txtPath ="/home/apache-tomcat-8.0.24/webapps/configSEX.txt";
	   String nuber=readTxT.readTxtLine(txtPath, 4);
	   String str=id.substring(0,2);
	   String strwo="00";
	   String urlStr="http://wwl.ycws.cc/ssm/v2/wwlfail";
    	if(str.equals(strwo)){
    		String nberid = id.substring(2);	
    		String type ="1";
    		JsonObject object2 = new JsonObject();
    		object2.addProperty("id", nberid);
    		object2.addProperty("usertype", type);
    		object2.addProperty("gun", nuber);
    		String jsonstr = object2.toString();
    		String json=doPostJsonone(urlStr, jsonstr);
    		if (json != null) {
 	    	   JsonParser parser = new JsonParser(); // 创建JSON解析器
                JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
                String timesetend=object.get("state").getAsString();
                System.out.println(timesetend);
    		}else{
    			System.out.println("没有成功导入的访客，保存到阿里出错了");
    		}
    	}else {
    		String type ="0";
    		JsonObject object2 = new JsonObject();
    		object2.addProperty("id", id);
    		object2.addProperty("usertype", type);
    		object2.addProperty("gun", nuber);
    		String jsonstr = object2.toString();
    		String json=doPostJsonone(urlStr, jsonstr);
    		if (json != null) {
  	    	   JsonParser parser = new JsonParser(); // 创建JSON解析器
                 JsonObject object = (JsonObject) parser.parse(json); // 创建JsonObject对象
                 String timesetend=object.get("state").getAsString();
                 System.out.println(timesetend);
     		}else{
     			System.out.println("没有成功导入的业主，保存到阿里出错了");
     		}
		}
		
    }
}
